<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Admin\Controller;
use Kcdns\Admin\Common\ModelCfg;

/**
 * 后台菜单
 */
class MenuController extends CommonController
{

    protected $editRedirect = 2;
    
    // 只有开发者账号可以操作菜单
    protected function checkDynamic ()
    {
        return is_administrator();
    }

    protected function _initialize ()
    {
        parent::_initialize();
        
        $data = M('Menu')->field(true)->order('sort asc')->select();
        $colors = [
                '#f39c12',
                '#00a65a',
                '#00c0ef',
                '#dd4b39',
                '#0073b7'
        ];
        $groups = [];
        $i = 0;
        foreach ($data as $k => $v)
        {
            $data[$k]['url'] = U('edit', array(
                    ModelCfg::escape('menu.id') => $v['id']
            ));
            
            $data[$k]['is_single'] = 1;
            $data[$k]['disabled'] = ! $v['status'];
            
            if ($v['group'])
            {
                $groupKey = $v['pid'].$v['group'];
                isset($groups[$groupKey]) or $groups[$groupKey] = $i ++% count($colors);
                $c = $groups[$groupKey];
                $data[$k]['title'] = "{$v['title']} <span style='color:#fff;background:{$colors[$c]};padding:1px 5px;font-size:12px;border-radius:10px;'>{$v['group']}</span>";
            }
        }
        $this->nodes = list_to_tree($data);
        $this->assign('nodes', $this->nodes);
        
        IS_POST or $this->insertSaveData = [
                'menu.pid' => I('pid'),
                'menu.status' => 1
        ];
    }

    public function index ()
    {
        // 批量排序
        if (IS_POST && I('post.flag') == 'sort')
        {
            $data = I('post.data');
            filter($data, [
                    [
                            'id' => 'required;int',
                            'sort' => 'required;int'
                    ]
            ]);
            foreach ($data as $v)
            {
                M('menu')->data([
                        'sort' => $v['sort']
                ])->where([
                        'id' => $v['id']
                ])->save();
            }
            $this->success();
        }
        
        if ($this->nodes)
        {
            $this->redirect('edit', array(
                    ModelCfg::escape('menu.id') => $this->nodes[0]['id']
            ));
        }
        $this->display();
    }
}